using System;
using System.Net.Mail;
using System.Reflection;

namespace BoxBinary.AspectCache.Core.ErrorLogging
{
    public class EmailErrorLogger : ErrorLoggerBase
    {
        private string _emailToAddress = string.Empty;

        public string EmailToAddress
        {
            get
            {
                if (string.IsNullOrEmpty(_emailToAddress))
                    _emailToAddress = ConfigSection.Current.EmailLowPriorityDevelopersAddress;
                return _emailToAddress;
            }
            set { _emailToAddress = value; }
        }

        public override void SaveLog()
        {
            if (base.IsLoggingEnabled)
            {
                base.PopulateFromException(Assembly.GetCallingAssembly());
                var message = new MailMessage();
                message.From = new MailAddress(ConfigSection.Current.EmailFromAddress);
                message.To.Add(new MailAddress(EmailToAddress));
                message.Subject = Title;
                message.IsBodyHtml = true;
                message.Body = Body;

                try
                {
                    var client = new SmtpClient();
                    client.Timeout = (int) TimeSpan.FromSeconds(8).TotalMilliseconds;
                    client.Send(message);
                }
                catch
                {
                    //TODO: Critical error, need to fall back 
                }
                Clear();
            }
        }
    }
}